package org.geektimes.configuration.microprofile.config.source.servlet;

import org.eclipse.microprofile.config.Config;

import javax.servlet.ServletContext;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created with IntelliJ IDEA.
 * Description:
 *
 * @Author: menglinggang
 * @Date: 2021-03-24
 * @Time: 8:14 下午
 */
public class ConfigUtils {

    private static final String CONFIG_NAME = "CONFIG_NAME";

    private static ExecutorService executorService;

    private static ThreadLocal<Config> localConfig = new ThreadLocal<>();

    public static void init(Config config) {
        synchronized (ConfigUtils.class) {
            if (executorService != null) {
                return;
            }
            executorService = Executors.newSingleThreadExecutor();
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    localConfig.set(config);
                }
            });

        }

    }

    public static void init(ServletContext servletContext, Config config) {
        servletContext.setAttribute(CONFIG_NAME, config);
    }

    public static Config getConfig(ServletContext servletContext) {
        Object attribute = servletContext.getAttribute(CONFIG_NAME);
        return attribute == null ? null : (Config) attribute;
    }

    public static Config get() {
        try {
            return executorService.submit(localConfig::get).get();
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
        return null;
    }


}
